import re
from django.contrib.auth.backends import ModelBackend
from itsdangerous import TimedJSONWebSignatureSerializer as TJSSerializer
from django.conf import settings
from .models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """重写此方法补充返回登录后的响应数据"""
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


def get_user_by_account(account):
    """
    :param account: 此参数可以是username或者mobile
    :return:  查到用户就返回user,否则返回None
    """
    try:
        if re.match(r'1[3-9]\d{9}', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """给Django认证后端类定义子类, 改写查询user逻辑,实现多账号登陆"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        """根据前端传来的account去动态查询user"""
        user = get_user_by_account(username)
        # 校验密码是否正确
        if user and user.check_password(password):
            return user


# 已经将 生成邮箱激活url 写在users.models 中了,所以将此处注释掉
# def generate_email_verify_url(user):
#     """生成邮箱激活url"""
#     serializer = TJSSerializer(settings.SECRET_KEY, 24 * 60 * 60)
#
#     data = {'user_id': user.id, 'email': user.email}
#
#     token = serializer.dumps(data).decode()
#     # 返回激活url
#     return "http://www.meiduo.site:8080/success_verify_email.html?token=%s" % token